package cn.jinjimi.app.main.fragment;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AbsListView;

import com.facebook.drawee.backends.pipeline.Fresco;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.controller.UserController;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.controller.event.InfoUpdateEvent;
import cn.jinjimi.app.controller.event.LoginSuccessEvent;
import cn.jinjimi.app.controller.event.LogoutEvent;
import cn.jinjimi.app.controller.event.NoticeEvent.NoticeEvent;
import cn.jinjimi.app.controller.event.NoticeEvent.NoticeNewFeatureEvent;
import cn.jinjimi.app.controller.event.NoticeEvent.NoticeNewVersionEvent;
import cn.jinjimi.app.controller.event.UserProfitEvent;
import cn.jinjimi.domain.data.dto.InfoModulesDTO;
import cn.jinjimi.domain.ServiceManager;
import cn.jinjimi.domain.store.ConfigStore;
import cn.jinjimi.app.entity.InfoMenu;
import cn.jinjimi.app.entity.InfoModule;
import cn.jinjimi.app.managers.NoticeManager;
import cn.jinjimi.app.store.entity.NoticeEntity;
import cn.jinjimi.app.main.activity.SettingActivity;
import cn.jinjimi.app.main.adapter.MeMenuAdapter;
import cn.jinjimi.app.main.extend.BaseFragment;
import cn.jinjimi.app.main.widget.biz.InfoHeadView;
import cn.jinjimi.app.main.widget.biz.MeEmptyView;
import cn.jinjimi.app.main.widget.XRecyclerView.FastScrollLinearLayoutManager;
import cn.jinjimi.app.main.widget.XRecyclerView.HeaderHeightListener;
import cn.jinjimi.app.main.widget.XRecyclerView.XRecyclerView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import bolts.Continuation;
import bolts.Task;

/**
 * @author zhenhua
 */
public class InfoFragment extends BaseFragment implements XRecyclerView.LoadingListener {
    private XRecyclerView mRecyclerView;
    private MeMenuAdapter mAdapter;
    private FastScrollLinearLayoutManager ll;
    private MeEmptyView emptyView;
    private View navBar;
    private InfoHeadView infoHeadView;

    private boolean isFirstIn = true;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_info;
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData();
    }

    protected void initView() {
        navBar = findView().findViewById(R.id.nav_bar);

        //头部
        infoHeadView = new InfoHeadView(getActivity());

        mRecyclerView = (XRecyclerView) findView().findViewById(R.id.recyclerview);
        mRecyclerView.addHeaderView(infoHeadView);
        mRecyclerView.setPullRefreshEnabled(true);
        mRecyclerView.setLoadingMoreEnabled(false);
        ll = new FastScrollLinearLayoutManager(getActivity());
        ll.setOrientation(LinearLayoutManager.VERTICAL);
        ll.setAutoMeasureEnabled(true);
        mRecyclerView.setLayoutManager(ll);
        mRecyclerView.setFooterWithText("");
        mRecyclerView.setFootViewHeight(getResources().getDimensionPixelOffset(R.dimen.dp_25));
        emptyView = new MeEmptyView(getContext());
        mRecyclerView.setEmptyView(emptyView);

        mAdapter = new MeMenuAdapter(getActivity());
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initListener() {
        emptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onRefresh();
            }
        });
        mRecyclerView.setLoadingListener(this);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE://空闲状态
                        Fresco.getImagePipeline().resume();
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING://滚动状态
                        Fresco.getImagePipeline().pause();
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL://触摸后滚动
                        break;
                }
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });

        mRecyclerView.setHeaderHeightListener(new HeaderHeightListener() {
            @Override
            public void onHeadHeight(int height) {
                //navBar.setAlpha(height <= 0 ? 1 : (150 - height) / 150f);
            }
        });
    }

    protected void initData() {
        NoticeManager.getNoticesByCode(NoticeEntity.TypeNewVersion, NoticeEntity.TypeBigDay);
        getMemberStatis();
        getDynamicMeMenu();
    }

    public void getMemberStatis() {

    }

    public void getDynamicMeMenu() {
        Task.callInBackground(new Callable<InfoModulesDTO>() {
            @Override
            public InfoModulesDTO call() throws Exception {
                return ServiceManager.getService(ConfigStore.class).fetchDynamicMeMenu();
            }
        }).continueWith(new Continuation<InfoModulesDTO, Object>() {
            @Override
            public Object then(Task<InfoModulesDTO> task) throws Exception {
                if (findView() == null) return null;
                mRecyclerView.refreshComplete();
                mRecyclerView.setEmptyViewHeight((int) (findView().getHeight() / 2f));
                InfoModulesDTO dto = task.getResult();
                if (task.isFaulted()) {
                    if (!mAdapter.isEmpty())
                        ToastUtils.toastMessage(getActivity(), R.string.load_fail);
                    else
                        mAdapter.setItems(null);
                } else if (task.isCompleted()) {
                    boolean hasData = dto != null && dto.modules != null && !dto.modules.isEmpty();
                    if (!hasData) {
                        mAdapter.clearItems();
                        mAdapter.notifyDataSetChanged();
                        return null;
                    }
                    mRecyclerView.setNoMore(true);
                    mRecyclerView.setRefreshTime(System.currentTimeMillis());
                    NoticeManager.getInstance().checkNewFeatures(getTitles(getMenus(dto.modules)));
                    mAdapter.setItems(getMenus(dto.modules));
                }
                return null;
            }
        }, Task.UI_THREAD_EXECUTOR);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginSuccessEvent(LoginSuccessEvent event) {
        //重新获取动态菜单
        onRefresh();
    }

    public List getMenus(List<InfoModule> modules) {
        List allMenus = new ArrayList<>();
        if (modules == null || modules.isEmpty())
            return allMenus;
        List<InfoMenu> topMemus = new ArrayList<>();
        List<InfoMenu> menus = new ArrayList<>();
        for (InfoModule module : modules) {
            if (module == null || module.menus == null || module.menus.isEmpty())
                continue;
            boolean hasTitle = StringUtils.isNotEmpty(module.title);
            if (hasTitle && module.code.equals("member")) {
                topMemus.addAll(module.menus);
                continue;
            } else if (hasTitle && module.code.equals("money")) {
                topMemus.addAll(module.menus);
                continue;
            } else if (hasTitle) {
                InfoMenu menu = new InfoMenu();
                menu.moduleCode = "title";
                menu.moduleTitle = module.title;
                menus.add(menu);
            }
            for (InfoMenu menu : module.menus) {
                if (menu == null) continue;
                menu.moduleCode = module.code;
                menu.moduleTitle = module.title;
                menus.add(menu);
            }
        }
        if (!topMemus.isEmpty())
            allMenus.add(topMemus);
        if (!menus.isEmpty())
            allMenus.addAll(menus);
        return allMenus;
    }

    public List<String> getTitles(List options) {
        List<String> titles = new ArrayList<>();
        for (Object object : options) {
            if (object instanceof List) {
                List list = (List) object;
                if (list != null && list.size() > 0) {
                    for (Object object1 : list) {
                        InfoMenu menu = (InfoMenu) object1;
                        if (menu == null || StringUtils.isEmpty(menu.title))
                            continue;
                        titles.add(menu.title);
                    }
                }
            } else if (object instanceof InfoMenu) {
                InfoMenu menu = (InfoMenu) object;
                if (menu == null || StringUtils.isEmpty(menu.title))
                    continue;
                titles.add(menu.title);
            }
        }
        return titles;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNoticeNewFeatureEvent(NoticeNewFeatureEvent event) {
        if (findView() == null) return;
        if (event.state == NoticeEvent.StateAdd) {
            //更新动态菜单
            if (mAdapter != null) {
                NoticeManager.getInstance().checkNewFeatures(getTitles(mAdapter.getItems()));
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNoticeNewVersionEvent(NoticeNewVersionEvent event) {
        if (event.state == NoticeEvent.StateAdd) {

        }
    }

    /* 更新个人信息 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onInfoUpdateEvent(InfoUpdateEvent event) {
        if (infoHeadView == null) return;
        infoHeadView.onRefresh();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUserProfitEvent(UserProfitEvent event) {
        if (infoHeadView == null) return;
        switch (event.state) {
            case DataEvent.SUCC:
                if (event.data != null && event.data.data != null) {
                    infoHeadView.onRefresh();
                }
                break;
            case DataEvent.FAIL:
                infoHeadView.onRefresh();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLogoutEvent(LogoutEvent event) {
        if (infoHeadView == null) return;
        switch (event.state) {
            case DataEvent.SUCC:
                infoHeadView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        infoHeadView.onRefresh();
                    }
                }, 100);
                break;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && AccountManager.getInstance().isLogin()) {
            /* 每次回到次tab获取一次推广费 */
            UserController.getUserProfit();
            if (isFirstIn) {
                isFirstIn = false;
                return;
            }
            getMemberStatis();
        }
    }

    @Override
    public void onRefresh() {
        if (AccountManager.getInstance().isLogin()) {
            UserController.getUserProfit();
        }
        getMemberStatis();
        getDynamicMeMenu();
    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_setting_black:
                openSetting();
                break;
        }
    }

    /* 打开设置 */
    @EventTrace(EventID.APP_OWNER_SET)
    public void openSetting() {
        getContext().startActivity(new Intent(getContext(), SettingActivity.class));
    }

    public void setStatusBarColor(boolean toBlack) {

    }
}